// 首页搜索-商城
import React, { useEffect, useState } from 'react';
import { View } from '@tarojs/components';
import { observer } from 'mobx-react-lite';
import TitleBar from '@/src/components/titleBar';
import Taro, { useDidShow } from '@tarojs/taro';
import './index.less';
import { AtSearchBar } from 'taro-ui';
import { searchListFun } from '@/src/common/method/wikiFun';
import BrandItem from '@/src/components/brandItem';
import InfiniteScroll from '@/src/components/infiniteScroll';
import CommonBlank from '@/src/components/pageBlank';
import store from '@/src/store';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
//百科-搜索页面
const WikiSearch = () => {
  const pageNum = 10;
  const [loadingText, setLoadingText] = useState<any>('');
  const [value, setValue] = useState('');
  const [dataList, setDataList] = useState<any>([]); //搜索列表
  const [maxPageNum, setMaxPageNum] = useState<number>(0);
  const [pageIndex, setPageIndex] = useState<number>(1);
  const [refresherTriggered, setRefresherTriggered] = useState<boolean>(false);
  const [flag, setFlag] = useState<boolean>(false);

  // 顶部
  const { windowHeight, screenWidth } = Taro.getSystemInfoSync();
  const rpx2px = (rpx: number) => (rpx / 750) * screenWidth;
  const contentPx =
    windowHeight -
    rpx2px(store.commonStore.pageAreaTop) -
    store.commonStore.safeAreaBottom;
  // 清除输入内容Index] = useState<number>(1);
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  // 清除输入内容
  const handleClear = () => {
    setFlag(false);
    setValue('');
    setDataList([]);
  };
  //获取搜索列表
  const searchFun = (value: any, pageIndex: number) => {
    setLoadingText('加载中...');
    searchListFun({
      productKeyWord: value,
      pageNo: pageIndex,
      pageSize: 10,
    }).then((res: any) => {
      setFlag(true);
      let result: any = [];
      setLoadingText('');
      setMaxPageNum(Math.ceil(res.totalCount / pageNum));
      if (pageIndex === 1) {
        setDataList(res.list);
      } else {
        result = [...dataList, ...res.list];
        setDataList(result);
      }
    });
  };

  // 处理输入
  const onChange = (value: any) => {
    setFlag(false);
    setValue(value);
    const reg: any = /^[\u4e00-\u9fa5a-zA-Z0-9]*$/;
    //有内容并且满足条件
    if (reg.test(value) && value.length > 0) {
      searchFun(value, pageIndex);
      //有内容不满足条件
    } else if (value.length > 0) {
      Taro.showToast({
        title: '请输入中文、英文、数字',
        icon: 'none',
      });
      //没有内容
    } else if (value.length === 0) {
      setDataList([]);
    }
  };
  //失去焦点方法
  const blurFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (value) {
      searchFun(value, pageIndex);
    } else {
      setDataList([]);
    }
  };
  //跳转到雪茄详情
  const gotoDetail = (item: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({
      url: `/subPagesWiki/cigaDetail/index?sku=${item.sku}`,
    });
  };

  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    const index = pageIndex + 1;
    if (index > maxPageNum) {
      return false;
    }
    setPageIndex(index);
    setLoadingText('加载中...');
    return searchFun(value, index);
  };

  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
  };
  //搜索结果内容
  const content = () => {
    return (
      <View className="wiki-search-list">
        {dataList &&
          dataList.map((item: any, index: any) => {
            return (
              <BrandItem
                gotoDetail={() => gotoDetail(item)}
                data={item}
                key={index}
              />
            );
          })}
      </View>
    );
  };
  // 一级下拉刷新处理
  const handleRefreshFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    setRefresherTriggered(true);
    //是否是首次下拉刷新
    searchFun(value, 1);
    setTimeout(() => {
      setRefresherTriggered(false);
    }, 1000);
  };
  return (
    <View
      className="wiki-search-container"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title="搜索"></TitleBar>
      <View className="search-body">
        <View className="wiki-search-box">
          <AtSearchBar
            placeholder="请输入搜索雪茄"
            className="wiki-search-bar"
            actionName="取消"
            value={value}
            focus={true}
            onConfirm={(value) => searchFun(value, 1)}
            showActionButton={true}
            onBlur={() => blurFun()}
            onFocus={() => setLoadingText('')}
            onChange={(value) => onChange(value)}
            onClear={() => handleClear()}
            onActionClick={handleClear}
          />
        </View>
        <View className="wiki-search-content">
          <InfiniteScroll
            style={{ height: `${contentPx}px` }}
            hasMore={pageIndex < maxPageNum}
            loadMore={() => loadMore()}
            refresherTriggered={refresherTriggered}
            handleRefresh={() => handleRefreshFun()}
            dataList={dataList}
            loading={loadingText === '' ? false : true}
            content={content()}
          />
          <CommonBlank
            visible={flag && value.length > 0 && dataList.length === 0}
            desc="抱歉，搜索无结果"
          />
        </View>
      </View>
    </View>
  );
};

export default observer(WikiSearch);
